# 每日定时启动客户端
import schedule
import pandas as pd
import os, subprocess, time
import pyautogui, psutil, sys
from PIL import Image
import pyscreeze, cv2
import pyperclip
import webbrowser



#   自动点击客户端菜单
def getAutoOutput(actionList):
    for actionRPA in actionList:
        if actionRPA == 'enter':
            pyautogui.press('enter')
            time.sleep(2)
        elif actionRPA[0:3] == 'tab':
            for i in range(int(actionRPA[3])):
                pyautogui.press('tab')
            time.sleep(2)
        elif actionRPA == 'shift':
            pyautogui.press('shift')
            time.sleep(2)
        else:
            pyperclip.copy(actionRPA)
            pyperclip.paste()
            time.sleep(2)


# 杀掉指定进程名的进程ID
def kill(proc_pid):
    process = psutil.Process(proc_pid)
    for proc in process.children(recursive=True):
        proc.kill()
        process.kill()


# 获取指定进程名的进程ID
def get_pid_by_name(process_name):
    for proc in psutil.process_iter(['pid', 'name']):
        if proc.info['name'] == process_name:
            return proc.info['pid']
    return None


#  图片识别点击控件
def getButton(targetImage):
    # 屏幕缩放系数 mac缩放是2 windows一般是1
    screenScale = 1
    # 事先读取按钮截图
    target = cv2.imread(targetImage, cv2.IMREAD_GRAYSCALE)
    # 先截图
    screenshot = pyscreeze.screenshot('my_screenshot.png')
    # 读取图片 灰色会快
    temp = cv2.imread(r'my_screenshot.png', cv2.IMREAD_GRAYSCALE)
    theight, twidth = target.shape[:2]
    tempheight, tempwidth = temp.shape[:2]
    # 先缩放屏幕截图 INTER_LINEAR INTER_AREA
    scaleTemp = cv2.resize(temp, (int(tempwidth / screenScale), int(tempheight / screenScale)))
    stempheight, stempwidth = scaleTemp.shape[:2]
    # 匹配图片
    res = cv2.matchTemplate(scaleTemp, target, cv2.TM_CCOEFF_NORMED)
    mn_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if (max_val >= 0.9):
        # 计算出中心点
        top_left = max_loc
        bottom_right = (top_left[0] + twidth, top_left[1] + theight)
        tagHalfW = int(twidth / 2)
        tagHalfH = int(theight / 2)
        tagCenterX = top_left[0] + tagHalfW
        tagCenterY = top_left[1] + tagHalfH
        # 左键点击屏幕上的这个位置
        pyautogui.click(tagCenterX, tagCenterY, button='left')
    else:
        print("没找到")
        log.info(f"没找到图片{targetImage}")


beginPath = os.path.split(os.path.realpath(__file__))[0]
fullPath = os.path.join(beginPath, "autoStart.xls")
print(fullPath)
configData = pd.read_excel(fullPath)
configDataTrue = configData[configData["是否启动"] == "Y"]
start_time = configDataTrue["启动时间(需要同一个时间)"].iloc[0]
print(str(start_time)[0:2])
indexconfig = len(configDataTrue)


# time.sleep(3)
def start_client():
    for i in range(indexconfig):
        client = configDataTrue["系统"].iloc[i]
        clientPath = configDataTrue["客户端exe目录"].iloc[i]
        userName = configDataTrue["账号"].iloc[i]
        password = configDataTrue["密码"].iloc[i]
        processName = configDataTrue["进程名称"].iloc[i]
        for proc in psutil.process_iter():
            try:
                if proc.name() == processName:
                    os.system(r'taskkill /F /IM {}'.format(processName))
            except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
                pass
        os.startfile(clientPath)
        time.sleep(10)
        if client == "OneQuant":
            print("开始登录操作")
            getAutoOutput(['tab2', userName, 'tab1', password, 'enter'])
            time.sleep(5)
        elif client == "手工T0":
            print("开始登录操作")
            getAutoOutput(['tab1', "shift", userName, 'tab1', password, 'enter'])
            time.sleep(5)
        elif client == "恒生PB":
            print("开始登录操作")
            getAutoOutput(['tab4', userName, 'tab1', password, 'enter'])
            time.sleep(5)
        elif client == "OQtest":
            print("开始登录操作")
            getAutoOutput(['tab2', userName, 'tab1', password, 'enter'])
            time.sleep(5)
        elif client == "Ptrade":
            getAutoOutput(['tab9', userName, 'tab1', password, 'enter'])
            time.sleep(30)
        elif client == "络町PB":
            getAutoOutput(["enter", 'tab2', userName, 'tab1', password, 'enter'])
            time.sleep(30)
        elif client == "迅投PB":
            getAutoOutput([userName, 'tab1', password, 'enter'])
            time.sleep(30)
        elif client == "宏汇ETF":
            if
            getAutoOutput(["enter", 'tab2', userName, 'tab1', password, 'enter'])
            time.sleep(30)
        elif client == "今古ETF":
            getAutoOutput([userName, 'tab1', password, 'enter'])
            time.sleep(30)
# start_client()
# 定时轮询启动任务
while True:
    if time.localtime().tm_hour == int(str(start_time).split(":")[0]) and time.localtime().tm_hour == int(str(start_time).split(":")[2]) and 启动标识 == False:
        start_client()
        time.sleep(60)
    else:
        print("未到定时启动时间")

